﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace CodingWheels.DataTypes.Core
{
	internal static class ConverterFactory
	{
		private static readonly Dictionary<Type, object> ConverterList = new Dictionary<Type, object>();

		public static IConverter<TUnit> GetConverter<TUnit>()
		{
			var type = typeof(Converter<>).MakeGenericType(typeof(TUnit));

			object converter;
			
			if(ConverterList.TryGetValue(type, out converter) == false)
			{
				var converterType =
					AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes()).Where(type.IsAssignableFrom).Single();

				converter = Activator.CreateInstance(converterType);
				ConverterList.Add(type, converter);
			}

			return converter as IConverter<TUnit>;
		}
	}
}
